<?php


namespace common\models\base;

use yii\base\InvalidConfigException;
use yii\db\QueryInterface;

class ActiveDataProvider extends \yii\data\ActiveDataProvider{

    const LIMIT_NUMBER = 20;

    public function __construct(array $config = [])
    {
        if(!isset($config['pagination'])){
            $config['pagination'] =[
                'pageSizeParam' => 'pageSize'
            ];
        }else{
            if($config['pagination']==false){
                unset($config['pagination']);
            }else if(!isset($config['pagination']['pageSizeParam'])){
                $config['pagination']['pageSizeParam'] = 'pageSize';
            }
        }
        parent::__construct($config);
    }

    public $withTotalCount = false;//是否返回totalCount


    protected function prepareModels()
    {
        if (!$this->query instanceof QueryInterface) {
            throw new InvalidConfigException('The "query" property must be an instance of a class that implements the QueryInterface e.g. yii\db\Query or its subclasses.');
        }
        $query = clone $this->query;
        if (($pagination = $this->getPagination()) !== false) {
            if($this->withTotalCount){
                $pagination->totalCount = $this->getTotalCount();
                if ($pagination->totalCount === 0) {
                    return [];
                }
            }else{
                $pagination->validatePage = false;
            }
            $query->limit($pagination->getLimit())->offset($pagination->getOffset());
        }
        if (($sort = $this->getSort()) !== false) {
            $query->addOrderBy($sort->getOrders());
        }

        return $query->all($this->db);
    }

}